<template>
  <div>
    <div style="text-align:left">
      <!-- <el-input v-model="tableDataName" size="small" placeholder="请输入姓名" style="width:240px"></el-input>
      <el-button type="primary" size="small" @click="searchUser">搜索</el-button> -->
      <!-- <el-button type="primary" size="small" @click="openData">展示数据</el-button> -->
      <el-button type="success" size="small" @click="addRow(menu)">新增</el-button>
      <!-- <el-button type="success" size="small" @click="handleAdd()">新增</el-button> -->
      <el-button type="primary" size="small" @click="removemenu()">批量删除</el-button>

<!--      <span v-bind="test">哈哈</span>-->
<!--      {{test}}-->
<!--      {{nowTime}}-->
    </div>
    <div>
<!--      {{nowTime}}-->
      <el-table :data="menu.slice((currentPage-1)*pageSize,currentPage*pageSize)" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
        <el-table-column type="selection" width="60">
        </el-table-column>
        <el-table-column type="index" width="30">
        </el-table-column>
        <el-table-column prop="aid"  label="编号" width="60" sortable>
        </el-table-column>
        <el-table-column prop="name"  label="图书" width="110" sortable>
        </el-table-column>
        <el-table-column prop="price"  label="单价" width="80" sortable>
        </el-table-column>
        <el-table-column prop="start"  label="开始时间" width="180" sortable>
        </el-table-column>
        <el-table-column prop="end"  label="截止时间" width="180" sortable>
        </el-table-column>
        <el-table-column prop="nums"  label="抢购数量" width="80" sortable>
        </el-table-column>
        <el-table-column prop="surplus"  label="库存" width="80" sortable>
        </el-table-column>
        <el-table-column label="距离开始倒计时" width="180" sortable>
          <template   slot-scope="scope">
            <span>
              <CountDown :endTime="scope.row.start"></CountDown>
            </span>
            </template>
        </el-table-column>
        <el-table-column prop="status"  label="状态" width="130" sortable>

          <template   slot-scope="scope">

            <span v-if="scope.row.status==1" style="color:blue">进行中</span>
            <span v-if="scope.row.status==0" style="color:orangered">未开始</span>
            <span v-if="scope.row.status==2" style="color:magenta">已结束</span>
<!--            <span v-if="scope.row.start==='2022-04-20 21:01:38'" style="color:#72d34b">活动进行中</span>-->
          </template>
        </el-table-column>

        <el-table-column label="操作" width="390">
          <template slot-scope="scope">
            <!-- <el-button type="success" size="small" @click="handleEdit(scope.$index, scope.row)">新增</el-button> -->
            <span v-if="scope.row.status==0" disabled="disabled">
              <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            </span>

            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row.aid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination align='center'
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[1,5,10,20]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="menu.length">
      </el-pagination>
    </div>
    <!--新增/编辑界面-->
    <el-dialog :title="titleMap[dialogStatus]" :visible.sync="FormVisible" :close-on-click-modal="false" class="edit-form"
               :before-close="handleClose">
      <el-form :model="Forma" label-width="80px" :rules="editFormRules" ref="Form">
        <el-form-item label="编号" prop="aid" hidden>
          <el-input v-model="Forma.aid" auto-complete="off"></el-input>
        </el-form-item>

<!--        <el-form-item label="图书" prop="name">-->
<!--          <el-input v-model="Form.name" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="图书" style="display:inline-block">
          <!--          <el-input type="select" v-model="Form.state"></el-input>-->
          <el-select v-model="Forma.bid" placeholder="请选择"  value-key="bid" @change="selectInventory(Forma.bid)" >
            <el-option
              v-for="item in FormBook"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单价" prop="price">
          <el-input v-model="Forma.price" auto-complete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="开始时间" prop="start">-->
<!--          <el-input v-model="Form.start" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
       抢购起止时间： <el-date-picker
          v-model="Forma.start"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择开始时间">
        </el-date-picker>
        抢购起止时间：
        <el-date-picker
          v-model="Forma.end"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择结束时间">
        </el-date-picker>
        <br/><br/>
        <el-form-item label="抢购数量" prop="nums">
          <el-input v-model="Forma.nums"  auto-complete="off"  @input="numberChange(arguments[0],inventory)"
                    @change="numberChange(arguments[0],inventory)" ></el-input>
        </el-form-item>
<!--        <el-form-item label="抢购数量" prop="nums">-->
<!--          <el-input v-model="Forma.nums"  auto-complete="off" ></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="此书库存" prop="inventory"  >
          <el-input v-model="inventory"  auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-input v-model="Forma.status" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel('Forma')">取消</el-button>
        <el-button v-if="addBtnshow" type="primary" @click.native="confirmAdd('Forma')">确定</el-button>
        <el-button v-if="editBtnshow" type="primary" @click.native="confirmEdit('Forma')">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
var _index;
import CountDown from "./CountDown";
export default {
  name: 'ActivityManger',

  data() {
    return {
      day: '',
      hour: '',
      minute: '',
      second: '',
      timer: '',
      start: false,

      test:'未开始',

      addForm: {
        image: ''
      },
      rules: {
        image: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },



      src1: require('../../assets/微信图片_20210731215732.jpg'),

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },

      options: [{
        value: '1',
        label: '启用'
      }, {
        value: '0',
        label: '禁用'
      }],



      currentPage:1,
      pageSize:5,
      titleMap: {
        addEquipment:'新增',
        editEquipment: "编辑"
      },
      //新增和编辑弹框标题
      // dialogStatus: "",
      Forma: {
        aid: '',
        bid: '',
        price: '',
        start: '',
        end: '',
        nums: '',
        status:   '',
        version:'',
        surplus:''
      },

      FormBook:{
        id:'',
        name:''
      },

      menu:[
      ],

      editFormRules:{
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
      },
      FormVisible: false,
      currentRow:[],
      ids:[],
      listLoading:'',
      addBtnshow:false,
      editBtnshow:false,
      editLoading:'',
      dialogStatus: '',
      selected:[],
      editid:'',
      searchForm:[],

      aData:new Date(),
      dateValue:'',
      mf:'',
      ss:'',
      nowTime:'',
      inventory:''
    }
  },
  props: {
    endTime: {
      // 倒计时结束时间
      default: '2022-09-05 21:17:40'
    },
    callback: () => {
      alert(1)
    }
  },
  components: {CountDown},
  created() {
    this.timeFormate(new Date());
    this.nowTimes();
    this.clear();

    this.$http.post('activity/select').then(data=>{
      console.log(data);
      this.menu = data;
      this.Forma=data;
      //alert(data);
      // this.options1.label=this.menu.name;
      // this.options1.value=this.menu.mid;
    });



    this.$http.post('book/select3').then(data=>{
      console.log(data);
      this.FormBook=data;
      //alert(data);
      // this.options1.label=this.menu.name;
      // this.options1.value=this.menu.mid;
    });



    console.log(this.aData) //Wed Aug 21 2019 10:00:58 GMT+0800 (中国标准时间)
    this.mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
    this.ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
    this.dateValue =this.aData.getFullYear() + "-" + (this.aData.getMonth() + 1) + "-" + this.aData.getDate()+" "+this.aData.getHours()+":"+this.mf+":"+this.ss;
    console.log(this.dateValue) //2019-8-20



  },

  mounted() {

    let remainTime = new Date(this.endTime).getTime() - new Date().getTime();
    //alert(remainTime)

    if (remainTime > 0) {
      this.day = Math.floor(remainTime / (1000 * 60 * 60 * 24))
      this.hour = Math.floor((remainTime / 1000 / 3600) % 24)
      this.minute = Math.floor((remainTime / 1000 / 60) % 60)
      this.second = Math.floor(remainTime / 1000 % 60)
      this.countDowm()
    }
  },

  methods: {
    // bchange(bid){
    //   console.log(bid)
    //   this.Forma.surplus=this.selectInventory(bid)
    // },
    selectInventory(bid){
      //alert(bid);
      return  this.$http.post('activity/selects', {bid:bid}).then(data=>{
        // this.Forma.nums=0;
        console.log(data);
        this.inventory=data;
        this.$emit('inputclear',{clear:''})
        this.Forma.surplus=data;
        //alert(data);
        // this.options1.label=this.menu.name;
        // this.options1.value=this.menu.mid;
      });
    },

    f1(){
      let actime= this.menu.start;

    },
    numberChange (val,maxNum) {
      //转换数字类型
      this.Forma.nums = Number(val)
      //重新渲染
      this.$nextTick(()=>{
        //比较输入的值和最大值，返回小的
        let num = Math.min(Number(val),maxNum)
        //输入负值的情况下， = 0（可根据实际需求更该）
        if(num<0) {
          this.Forma.nums = 0
        }else {
          //反之
          this.Forma.nums = num
        }
      })
    },

    //显示当前时间（年月日时分秒）
    timeFormate(timeStamp) {
      let year = new Date(timeStamp).getFullYear();
      let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1;
      let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate();
      let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours();
      let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes();
      let ss =new Date(timeStamp).getSeconds() < 10? "0" + new Date(timeStamp).getSeconds(): new Date(timeStamp).getSeconds();
      let week = new Date(timeStamp).getDay();
      let weeks = ["日","一","二","三","四","五","六"];
      let getWeek = "星期" + weeks[week];
      this.nowTime = year + "-" + month + "-" + date +" "+hh+":"+mm+':'+ss;
    },
    nowTimes(){
      this.timeFormate(new Date());
      setInterval(this.nowTimes,1000);
      this.clear()
    },
    clear(){
      clearInterval(this.nowTimes)
      this.nowTimes = null;
    },



    handleCheckAllChange (val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },

    handleChange (file, fileList) {
      this.addForm.image = URL.createObjectURL(file.raw)
      // var files = this.addForm.image
      // files.push(this.addForm.image)
    },
    beforeupload (file) {
      return true
    },
    submitForms (addForm) { // 新增表单提交
      this.axios({
        method: 'post',
        url: 'url',
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data: {}
      })
        .then(res => {
          this.$refs[addForm].validate((valid) => {
            if (valid) {
              this.$refs.upload.submit()
              // 不可缺少
            } else {
              console.log('error submit!!')
              return false
            }
          })
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    selsChange: function (val) {  //点击选中
      console.log(val);
      this.selected = val;
    },
    // 点击新增
    addRow (menu, event) {
      this.FormVisible = true;
      this.Forma = {
        aid: 0,
        price: 0,
        bid: 0,
        start:'',
        end:'',
        status:''
      };

      this.dialogStatus = "addEquipment"
      this.addBtnshow = true
      this.editBtnshow = false

    },
    // 点击确定（新增）
    confirmAdd () {

      // this.book.push({
      //   name: this.Form.name,
      //   price: this.Form.price,
      //   reserve: this.Form.reserve,
      //   data: this.Form.data,
      //   desc: this.Form.desc
      // })
      console.log(this.Forma)
      if(this.Forma.nums<=this.inventory&&this.inventory!==0){
      this.$http.post("/activity/insert", this.Forma).then(add => {
        //alert(add);
        if (add > 0) {
          alert("添加成功");
          window.location.reload();
        } else {
          alert("添加失败")
        }
        this.FormVisible = false;
      })
      }
      else if(this.inventory===0){
        alert("该书已无库存！")
      }
      else {
        alert("抢购数量大于库存，请重新输入");
      }

    },
    //点击编辑
    handleEdit: function (index, row) {
      this.FormVisible = true;
      this.Forma = Object.assign({}, row); //这句是关键！！！
      _index = index;
      console.log(index);
      console.log(_index);

      this.dialogStatus = "editEquipment"
      this.addBtnshow = false
      this.editBtnshow = true
    },
    // 点击确定（编辑）
    confirmEdit () {
      console.log(this.Forma.toString()+"哈")
      this.$http.post("/activity/update", this.Forma).then(add => {
        if (add !=null) {
          alert("修改成功");
          window.location.reload();
        } else {
          alert("修改失败")
        }
      });

    },
    //点击关闭dialog
    handleClose (done) {
      //  done();
      //  location.reload();
      this.FormVisible = false;
    },
    //点击取消
    handleCancel (formName) {
      this.FormVisible = false;
    },
    // 删除
    handleDelete (index, rows) {

      // console.log(index, row);
      this.Forma.aid = rows
      // alert(this.Form.id);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //alert(this.Form.aid)
        this.$http.post("/activity/delete",{aid: this.Forma.aid}).then(add => {
          if (add > 0) {
            type: 'success';
            message: '删除成功!';
            window.location.reload();
          } else {
            alert("修改失败")
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    removemenu () {
      this.$confirm('此操作将永久删除 ' + this.selected.length + ' 条数据, 是否继续?', '提示', {type: 'warning'})
        .then(() => {
          console.log(this.selected);
          var ids = [];
          //提取选中项的id
          $.each(this.selected, (i, menu) => {
            ids.push(menu.aid);
          });
          // 向请求服务端删除
          //  var resource = this.$resource(this.url);
          this.$http.post("/menu/delete", {ids: ids.join(",")})
            .then((response) => {
              this.$message.success('删除了' + this.selected.length + '条数据!');
              this.getmenu();
            })
            .catch((response) => {
              this.$message.error('删除失败!');
            });
        })
        .catch(() => {
          this.$message('已取消操作!');
        });
    },

    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    stateFormat (row, column, cellValue) {
      // console.log(row , column , cellValue)
      if (!cellValue) return "";
      if (cellValue.length > 40) {
        //最长固定显示4个字符
        return cellValue.slice(0, 40) + "...";
      }
      return cellValue;
    },
    clickContent: function (row, column, cell, event) {
      clickContent(row, column, cell, event)
      {
        if (column.label === '数据内容') {  // 只有点击数据内容列时才会展开
          row.flag = !row.flag  // 这个参数是当时将数据存储到表格中时特意加上控制表格的展开和省略的
        }
      }
    },
    ending() {
      this.$emit("TimeEnding");
    },
    countDowm() {
      let self = this
      clearInterval(this.timer)
      this.timer = setInterval(function () {
        if (self.hour === 0) {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            if (self.day === 0) {
              self.second = 0
              self.$emit('countDowmEnd', true)
              this.start = true;
              clearInterval(self.timer)
              self.ending();
            } else {
              self.day -= 1;
              self.hour = 23;
              self.minute = 59;
              self.second = 59;
            }
          } else {
            self.second -= 1
          }
        } else {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59
            self.minute -= 1
          } else if (self.minute === 0 && self.second === 0) {
            self.hour -= 1
            self.minute = 59
            self.second = 59
          } else {
            self.second -= 1
          }
        }
      }, 1000)
    },
    formatNum(num) {
      return num < 10 ? '0' + num : '' + num;
    }
  },


  computed: {
    dayString() {
      return this.formatNum(this.day)
    },
    hourString() {
      return this.formatNum(this.hour)
    },
    minuteString() {
      return this.formatNum(this.minute)
    },
    secondString() {
      return this.formatNum(this.second)
    }
  }


}

</script>
<style>

</style>
